<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden;"
      v-model="content"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, shallowRef, watch } from 'vue';
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { ipfsClient } from '@/api/IPFSClient';
import { config } from '@/config/config';

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig = {};
// eslint-disable-next-line
type InsertFnType = (url: string, alt: string, href: string) => void;
const editorConfig = { 
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      // 自定义上传
      async customUpload(file: File, insertFn: InsertFnType) {  
        const result = await ipfsClient.add(file);
        const ipfsUrl = `${config.ipfs_gateway}${result.path}`;
        insertFn(ipfsUrl, file.name, ipfsUrl)
      }
    },
    uploadVideo: {
      // 自定义上传
      async customUpload(file: File, insertFn: InsertFnType) {  
        const result = await ipfsClient.add(file);
        const ipfsUrl = `${config.ipfs_gateway}${result.path}`;
        insertFn(ipfsUrl, file.name, ipfsUrl)
      }
    }
  }
};
const mode = 'default';

// eslint-disable-next-line
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
});

// eslint-disable-next-line
const emit = defineEmits(['update:modelValue']);

const content = ref(props.modelValue);

watch(() => props.modelValue, (newVal) => {
  content.value = newVal;
});

watch(content, (newVal) => {
  emit('update:modelValue', newVal);
});

onMounted(() => {
  // 初始加载 content 内容
  if (props.modelValue) {
    content.value = props.modelValue;
  }
});

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style scoped>
/* 可以在这里添加特定于编辑器的样式 */
</style>